<template>
	<view class="uni-tab-bar">
		<view class="uni-tab">
			<uni-segmented-control 
			:current="tabCurrentIndex" 
			:values="tabItems" 
			v-on:clickItem="onClickTab" 
			:styleType="'text'" >
			</uni-segmented-control>
		</view>
		<swiper :current="swiperCurrentIndex" class="swiper-box" :duration="300" @change="swiperChange">
			<swiper-item v-for="(item,index) in swiperList.marquee" :key="index" :item-id="item.key">
				<scroll-view class="list" scroll-y>
					<view class="uni-padding-wrap uni-common-mt">
						<view class="uni-title title">{{item.label}}</view>
						<view class="filterBtn" @tap="drawerDisplay(true)"><uni-icon size="30" :type="'compose'" :color="'#000'"></uni-icon></view>
						<image class="img" :src="item.img" @error="errorImg" mode="aspectFit" :id="item.key"></image>
						<rich-text class="paragraph" :nodes="item.memo"></rich-text>
						<br/>
						<br/>
						<br/>
						<br/>
						<br/>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
		<view class="arrowTips">
			<view class="arrowLeft" @tap="swiperChangeManual('left')" :class="[arrowLeftDisabled ? 'disabled' : '']">
				<uni-icon size="22" :type="'back'" :color="'#fff'"></uni-icon>
			</view>
			<view class="arrowRight" @tap="swiperChangeManual('right')" :class="[arrowRightDisabled ? 'disabled' : '']">
				<uni-icon size="22" :type="'forward'" :color="'#fff'"></uni-icon>
			</view>
		</view>
        <view class="bottomBtn">
        	<view class="btnWrap">
        		<button type="warn" class="voiceBtn" @tap="startRecognize" :loading="loading">
							<uni-icon size="22" :type="'sound'" :color="'#fff'"></uni-icon>
						</button>
						<button class="throwBtn" type="primary" @tap="throwAds" :loading="loading">
							<uni-icon size="25" :type="'videocam'" :color="'#fff'"></uni-icon>
							投放广告
						</button>
        	</view>
        </view>
		<view class="animateBlock" v-if="animateBlockToggle"> 
			<image class="bigScreen" :src="animateScreen" :class="[animateBlockToggle ? 'bounceInDown animated' : '']" ></image>
			<image class="throwTheAd" :src="'../../static/vedio.gif'" :class="[throwTheAd ? 'fadeOutUpBig animated' : '']" ></image>
			<view class="animateBlockBg" :class="[animateBlockToggle ? 'fadeIn animated' : '']"></view>
		</view>
		<uni-drawer :visible="drawerShow" mode="right" @close="drawerDisplay(false)">
			<scroll-view scroll-y style="height: 100%;">
				<view class="uni-title drawerTitle">选择日期（点击多次可重选）</view>
				<reserve-date @change="calendarChanged" :dateRange="calendarRange" :isNowDate="true" :disableBefore="true"/>
				<view class="line"></view>
				<view class="uni-title drawerTitle">选择区域（点击文字或滑动切换）</view>
				<checkbox-group @change="checkboxChange" class="areaCheckGroup">
					<view class="item" v-for="(item,index) in areaItems" :key="index">
						<label class="check"><checkbox :value="item.value" :checked="item.checked" /></label>
						<view class="text" @click="changeAreaMap(index)" :class="[areaImgCurrentIndex == index?'on':'']">{{item.name}}</view>
					</view>
				</checkbox-group>
				<swiper :current="areaImgCurrentIndex" :duration="300" @change="areaImgChange" class="areaSwiper">
					<swiper-item v-for="(item,index) in areaItems" :key="index" :item-id="item.value">
							<image class="img" :src="item.img" @error="errorImg" mode="widthFix" :id="item.key"></image>
					</swiper-item>
				</swiper>
			</scroll-view>
		</uni-drawer>
	</view>
</template>


<script>
	import store from '@/vuex'
	import uniSegmentedControl from '@dcloudio/uni-ui/lib/uni-segmented-control/uni-segmented-control.vue'
	import uniIcon from '@dcloudio/uni-ui/lib/uni-icon/uni-icon.vue'
	import uniDrawer from "@dcloudio/uni-ui/lib/uni-drawer/uni-drawer.vue"
	import reserveDate from '@/components/reserve-date/reserve-date.vue'
	import CryptoJS from '@/common/crypto-js.min.js'
	import {api} from '@/api/index.js'

	export default {
		components: {
			uniSegmentedControl,
			uniIcon,
			uniDrawer,
			reserveDate
		},
		data() {
			return {
				test:'<h2>safag</h2>safaf<br/><img src="https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/uni@2x.png" />',
				path:'',
				tabItems: ['个人客户','企业客户'],
				tabCurrentIndex: 0,
				swiperCurrentIndex: 0,
				swiperCurrentId: '',
				swiperList:[],
				voiceList:{},
				voiceValue: '',
				arrowLeftDisabled:true,
				arrowRightDisabled:true,
				animateBlockToggle:false,
				animateScreen:'../../static/big-screen-empty.png',
				throwTheAd:false,
				drawerShow:false,
				calendarRange:{},
				areaItems:[],
				areaImgCurrentIndex:0,
				choosenArea:[]
			}
		},
		computed:{
			loading:{
				get () {
				  return store.getters.getLoadingStatus
				},
				set (value) {
				  store.commit('updateLoadingStatus', value)
				} 
			},
			data:{
				get () {
				  return store.getters.getData
				},
				set (value) {
				  store.commit('updateData', value)
				} 
			}
		},
		onLoad: function (option) {
			this.changeCalendarRange()
			this.path = uni.getStorageSync('default_path')
			uni.request({
				url: (this.path.indexOf('mock') >= 0 ? 'default.json' : api.getData) + '?time=' + new Date().getTime(), 
				/* header:{
					'Content-Type':'application/x-www-form-urlencoded'
				}, */
				success: (res) => {
					//console.log(JSON.stringify(res));
					/* for(let item of this.data['switch']){
						this.tabItems.push(item.label)
					} */
					this.data = res.data
					this.setData()
					this.getArea()
				},
				fail: () => {
					uni.showToast({
						title: '服务器链接失败' ,
						duration: 2000
					}) 
				}
			});
		},
		onShow: function() {
			this.setData()
		},
		onNavigationBarButtonTap(e) {
			switch (e.index){
				case 0:
					uni.navigateTo({
						url: '/pages/setting/setting'
					});
					break;
				case 1:
					uni.navigateTo({
						url: '/pages/my/my'
					});
					break;
				case 2:
					// #ifdef APP-PLUS
					plus.runtime.restart();
					// #endif
					// #ifdef H5
					window.location.href = '/';
					// #endif
					break;
				default:
					break;
			}
		},
		methods: {
			getChoosenAreaName(){
				let name = ''
				this.choosenArea.forEach(choosenItem=>{
					this.areaItems.some(areaItem=>{
						if(areaItem.value == choosenItem){
							name += areaItem.name + ','
							return true
						}
					})
				})
				return name
			},
			getArea(){
				/* uni.request({
					url: this.data.server + 'getArea' + '?time=' + new Date().getTime(), 
					success: (res) => {
						if(res.statusCode == 200){
							this.areaItems = res.data */
							this.areaItems =  [
								{value: '0',name: 'CBD',img:'../../static/test/CBD.jpg'},
								{value: '1',name: '学校',img:'../../static/test/school.jpg'},
								{value: '2',name: '居民区',img:'../../static/test/residence.jpg'},
								{value: '3',name: '电影院',img:'../../static/test/cinema.jpg'}
							]
							this.areaItems.forEach(item=>{
								item.checked = true
								this.choosenArea.push(item.value)
							})
			/* 			}
					},
					fail: () => {
						uni.showToast({
							title: '服务器链接失败' ,
							duration: 2000
						}) 
					}
				}); */
			},
			checkedOrNot(val){
				let flag = false
				this.choosenArea.some(item=>{
					if(val == item){
						flag = true
						return true
					}
				})
				return flag
			},
			checkboxChange(e) {
				this.choosenArea = e.detail.value
				this.areaItems.forEach(areaItem=>{
					areaItem.checked = false
				})
				this.areaItems.forEach(areaItem=>{
					this.choosenArea.some(ChoosenItem=>{
						if(areaItem.value == ChoosenItem) {
							areaItem.checked = true
							return true
						}
					})
				})
				
			},
			areaImgChange(e){
				this.areaImgCurrentIndex = e.detail.current
			},
			changeAreaMap(index){
				this.areaImgCurrentIndex = index
			},
			changeCalendarRange(obj){
				if(!obj){
					let nowDate = new Date(),
						_nowDate = `${nowDate.getFullYear()}-${nowDate.getMonth() + 1}-${nowDate.getDate()}`,
						monthStartDate = new Date(nowDate.getYear(), nowDate.getMonth(), 1),
						nextMonthStartDate = new Date(nowDate.getYear(), nowDate.getMonth() + 1, 1),
						monthEndDate = (nextMonthStartDate - monthStartDate) / (1000 * 60 * 60 * 24),
						_monthEndDate = `${nowDate.getFullYear()}-${nowDate.getMonth() + 1}-${monthEndDate}`
					this.calendarRange = {begin: _nowDate, end: _monthEndDate}
				}else this.calendarRange = obj
			},
			calendarChanged(dates) {
				let tempRange = dates.length > 0?{begin:dates[0].date,end:dates[dates.length-1].date}:null
				this.changeCalendarRange(tempRange)
			},
      drawerDisplay(flag){
				this.drawerShow = flag
			}, 
			setData(){
				if(this.data['switch'] && this.data['switch'][0]){
					this.swiperList = JSON.parse(JSON.stringify(this.data['switch'][0]))
					if(this.swiperList.marquee){
						for(let item of this.swiperList.marquee){
							item.img = this.data.server + item.img
						}
						this.swiperCurrentId = this.swiperList.marquee[0].key
					}
					this.swiperCurrentIndex = 0
					this.tabCurrentIndex = 0
					this.arrowRightDisabled = false
				}
				if(this.data['voice']) this.voiceList = this.data['voice']
				/* uni.showToast({
					title: '服务器链接成功' ,
					duration: 2000
				}) */
			},
			errorImg(e){
				let imageId = e.target.id
				for(let item of this.swiperList.marquee){
					if(item.key == imageId) item.img = '../../static/noPic.png'
				}
			},
			onClickTab(index) {
				if (this.tabCurrentIndex !== index) {
					this.tabCurrentIndex = index;
					if(this.data['switch'] && this.data['switch'][index]){
						this.swiperList = JSON.parse(JSON.stringify(this.data['switch'][index]))
						if(this.swiperList.marquee){
							for(let item of this.swiperList.marquee){
								item.img = this.data.server + item.img
							}
							this.swiperCurrentId = this.swiperList.marquee[0].key
						}
						this.swiperCurrentIndex = 0
					}
				}
			},
			swiperChangeManual(direction){
				if(direction == 'left' && this.swiperCurrentIndex > 0){
					this.swiperCurrentIndex--
				}else if(direction == 'right' && (this.swiperList.marquee.length - 1) > this.swiperCurrentIndex){
					this.swiperCurrentIndex++
				}
			},
			swiperChange(e){
				this.swiperCurrentIndex = e.detail.current
				this.swiperCurrentId = this.swiperList.marquee[this.swiperCurrentIndex].key
				if(this.swiperList.marquee)
					(this.swiperList.marquee.length - 1) <= this.swiperCurrentIndex ? this.arrowRightDisabled = true : this.arrowRightDisabled = false
				this.swiperCurrentIndex <= 0 ? this.arrowLeftDisabled = true : this.arrowLeftDisabled = false
			},
			startRecognize: function () {
				//this.loading = true
				var options = {};
				var that = this;
				options.engine = 'baidu';
				that.voiceValue = "";
				plus.speech.startRecognize(options, function (s) {
					that.voiceValue += "语音识别结果：" + s;
					let matchValue = ''
					if(JSON.stringify(that.voiceList) != '{}') 
						that.voiceList.sounds.some(function(item){
							if(s.indexOf(item.text) >= 0){
								matchValue += '匹配到广告媒体：' + item.key
								that.throwAds(item.key)
								return true
							}
						})
					uni.showToast({
						title: that.voiceValue + matchValue,
						icon: 'none',
						duration: 3000
					})
					//that.loading = false
					console.log(that.voiceValue + matchValue);
				}, function (e) {
					//that.loading = false
					console.log("语音识别失败：" + e.message);
				});
			},
			throwAds(soundKey){
				this.loading = true
				/* uni.showModal({
					content: "是否投放该广告？",
					confirmText: "确定",
					cancelText: "取消",
					success: function(res){
						if (res.confirm) { */
							let flag = false
							if(typeof soundKey == 'string'){
								if(JSON.stringify(this.voiceList) == '{}' && this.voiceList.sounds.length <= 0) flag = true
							}else{
								if(this.swiperList.length <= 0) flag = true
							}
							
							if(flag){
								uni.showToast({
									title: '当前没有匹配的广告' ,
									duration: 3000,
									icon: 'none'
								}) 
								this.loading = false
								return false
							}
						
							let desKey = "FocusMedia"
							let desString = typeof soundKey == 'string'?
											(this.data.target[0] + '|' + this.voiceList.key + '|' + soundKey) :
											(this.data.target[0] + '|' + this.swiperList.key + '|' + this.swiperCurrentId)
							console.log(desString);
							
							//加密
							var encrypt = CryptoJS.DES.encrypt(desString, CryptoJS.enc.Utf8.parse(desKey), {
							  mode: CryptoJS.mode.ECB,
							  padding: CryptoJS.pad.Pkcs7
							}).toString();
							console.log(encrypt);
							uni.getStorage({
								key: 'default_path',
								complete: (res) => {
									uni.request({
										url: this.data.server + 'des', 
										data:{
											cmd:encrypt
										},
										/* header:{
											'Content-Type':'application/x-www-form-urlencoded'
										}, */
										success: (res) => {
											console.log(JSON.stringify(res));
											this.loading = false
											this.animateBlockToggle = true
											setTimeout(()=>{
												this.throwTheAd = true
											},500)
											setTimeout(()=>{
												this.animateScreen = '../../static/big-screen-progress.png'
											},1000)
											setTimeout(()=>{
												this.animateBlockToggle = false
												this.throwTheAd = false
												this.animateScreen = '../../static/big-screen-empty.png'
												uni.showModal({
													title: res.data.result == 0 ? '投放成功' : '投放失败',
													showCancel: false,
													content: '开始日期：' + this.calendarRange.begin + '，结束日期：' + this.calendarRange.end + '。投放区域：' + this.getChoosenAreaName()
												});
												/* uni.showToast({
													title: res.data.result == 0 ? '投放成功' : '投放失败',
													duration: 3000
												}) */
											},2000)
										},fail: (res) => {
											console.log(JSON.stringify(res));
											this.loading = false
										}
									});
								}
							})
					/* 	} 
					}
				}) */
			}
		}
	}
</script>

<style lang="scss">
	.uni-padding-wrap{
		position: relative;
		.title{font-weight:bold;border-bottom: 1px solid #c5c5c5;font-size: 40upx;margin-bottom: 16upx;padding:0 0 20upx;}
		.filterBtn{position: absolute;top:5upx;right:26upx;}
	}
	.img{margin: 10upx auto;max-width:100%;display: block;}
	.arrowTips{
		.arrowLeft,.arrowRight{position: absolute;top:42%;padding:40upx 0;border-radius: 5px;background: #999;opacity: 0.7;}
		.arrowLeft.disabled,.arrowRight.disabled{opacity: 0.3;}
		.arrowLeft{left:0;border-top-left-radius: 0;border-bottom-left-radius: 0;}
		.arrowRight{right:0;border-top-right-radius: 0;border-bottom-right-radius: 0;}
	}
	.bottomBtn{
		position: fixed;bottom:0;left: 0;width:100%;background: #fff;
		.btnWrap{
			padding: 20upx 32upx;display: flex;
			.throwBtn{
				height:90upx;line-height: 90upx;flex-grow:2;
				.uni-icon{margin-right: 10upx;}
			}
			.voiceBtn{height:90upx;line-height: 90upx;margin-right: 20upx;}
		}
	}
	.animateBlock{
		.animateBlockBg{background:url(../../static/animateBlockBg.png);opacity: 0.4;position: fixed;z-index: 20000;top: 0;left: 0;right: 0;bottom: 0;width: 100%;height: 100%;}
		.bigScreen{width: 80%;position: fixed;top: 0%;left: 10%; z-index: 20001;}
		.throwTheAd{width: 80%;position: fixed;z-index: 20002;bottom: 20upx;left: 10%;}
	}
	.drawerTitle{padding:10upx;font-weight: bold;margin-top:20upx;}
	.uni-drawer__content{width:75% !important;}
	.line{height:2upx;background:#eee;width:100%;margin:20upx 0;}
	.areaCheckGroup{
		.item{
			display: inline-block;margin:10upx 30upx 10upx 10upx;
			.check{display: inline-block;padding: 0;margin-right: 10upx;}
			.text{
				display: inline-block;
				&.on{color:red;}
			}
		}
	}
	.areaSwiper{
		height:480upx;
	}
</style>
